<template>
  <div class="cases-page">
    <!-- 页面头部背景 -->
    <div class="page-header">
      <div class="container">
        <h1 class="page-title">领养案例</h1>
        <p class="page-subtitle">每一个成功的领养都是一个温暖的故事</p>
      </div>
    </div>

    <div class="container mt-4">
      <div class="row">
        <!-- 主内容区域 -->
        <div class="col-xs-12 col-sm-8 col-md-9">
          <!-- 加载状态 -->
          <div v-if="loading" class="text-center py-5">
            <div class="spinner-border text-primary" role="status">
              <span class="visually-hidden">Loading...</span>
            </div>
            <p class="mt-2">正在加载领养案例...</p>
          </div>

          <!-- 错误状态 -->
          <div v-else-if="error" class="alert alert-danger">
            <h5>加载失败</h5>
            <p>{{ error }}</p>
            <button @click="fetchCases" class="btn btn-outline-danger">重试</button>
          </div>

          <!-- 案例列表 -->
          <div v-else>
            <!-- 搜索结果提示 -->
            <div v-if="searchKeyword" class="alert alert-info mb-3">
              搜索"{{ searchKeyword }}"的结果：共找到 {{ totalCases }} 个案例
              <button @click="clearSearch" class="btn btn-sm btn-outline-info ms-2">清除搜索</button>
            </div>

            <!-- 案例网格 -->
            <div class="row">
              <div
                v-for="adoptionCase in cases"
                :key="adoptionCase.id"
                class="col-sm-6 col-lg-4 mb-4"
              >
                <div class="adoption-card">
                  <div class="adoption-image-wrapper">
                    <img
                      :src="adoptionCase.image"
                      :alt="adoptionCase.name"
                      class="adoption-image"
                      @error="handleImageError"
                    >
                    <div class="adoption-status" :class="getStatusClass(adoptionCase.status)">
                      {{ adoptionCase.status }}
                    </div>
                  </div>
                  <div class="adoption-info">
                    <h5 class="adoption-name">{{ adoptionCase.name }}</h5>
                    <div class="adoption-details">
                      <span v-if="adoptionCase.age" class="detail-item">{{ adoptionCase.age }}</span>
                      <span v-if="adoptionCase.gender" class="detail-item">{{ adoptionCase.gender }}</span>
                      <span v-if="adoptionCase.breed" class="detail-item">{{ adoptionCase.breed }}</span>
                    </div>
                    <p class="adoption-description">{{ adoptionCase.description?.substring(0, 100) }}...</p>
                    <div class="adoption-actions">
                      <router-link
                        :to="`/adoption-cases/${adoptionCase.id}`"
                        class="btn btn-primary btn-sm"
                      >
                        查看详情
                      </router-link>
                    </div>
                  </div>
                </div>
              </div>
            </div>

            <!-- 无数据提示 -->
            <div v-if="cases.length === 0 && !loading" class="text-center py-5">
              <div class="no-data">
                <img src="@/assets/images/no-data.png" alt="暂无数据" class="no-data-image">
                <h5>暂无领养案例</h5>
                <p class="text-muted">{{ searchKeyword ? '没有找到匹配的案例，请尝试其他关键词' : '敬请期待更多温暖的故事' }}</p>
              </div>
            </div>

            <!-- 分页 -->
            <nav v-if="totalPages > 1" aria-label="领养案例分页">
              <ul class="pagination justify-content-center">
                <li class="page-item" :class="{ disabled: currentPage === 1 }">
                  <button class="page-link" @click="goToPage(currentPage - 1)">上一页</button>
                </li>
                <li
                  v-for="page in getPageNumbers()"
                  :key="page"
                  class="page-item"
                  :class="{ active: page === currentPage }"
                >
                  <button class="page-link" @click="goToPage(page)">{{ page }}</button>
                </li>
                <li class="page-item" :class="{ disabled: currentPage === totalPages }">
                  <button class="page-link" @click="goToPage(currentPage + 1)">下一页</button>
                </li>
              </ul>
            </nav>
          </div>
        </div>

        <!-- 侧边栏 -->
        <div class="col-xs-12 col-sm-4 col-md-3">
          <!-- 搜索框 -->
          <div class="search-box mb-4">
            <h5 class="sidebar-title">搜索领养案例</h5>
            <div class="input-group">
              <input
                type="text"
                v-model="searchInput"
                @keyup.enter="performSearch"
                class="form-control"
                placeholder="输入宠物名称或特征"
              >
              <button @click="performSearch" class="btn btn-primary" :disabled="loading">
                <i class="fas fa-search"></i> 搜索
              </button>
            </div>
          </div>

          <!-- 快速筛选 -->
          <div class="quick-filters mb-4">
            <h5 class="sidebar-title">快速筛选</h5>
            <div class="filter-buttons">
              <button
                v-for="status in statusFilters"
                :key="status.value"
                @click="filterByStatus(status.value)"
                class="btn btn-outline-secondary btn-sm me-2 mb-2"
                :class="{ active: currentStatusFilter === status.value }"
              >
                {{ status.label }}
              </button>
            </div>
          </div>

          <!-- 宠物知识推荐 -->
          <div class="knowledge-recommend">
            <h5 class="sidebar-title">养宠知识</h5>
            <div v-if="knowledgeLoading" class="text-center">
              <small class="text-muted">加载中...</small>
            </div>
            <ul v-else-if="recommendedKnowledge.length > 0" class="knowledge-list">
              <li v-for="article in recommendedKnowledge" :key="article.id">
                <router-link :to="`/pet-column/article/${article.id}`" :title="article.title">
                  {{ article.title }}
                </router-link>
                <small class="text-muted">{{ formatDate(article.date) }}</small>
              </li>
            </ul>
          </div>

          <!-- 联系信息 -->
          <div class="contact-info">
            <h5 class="sidebar-title">联系我们</h5>
            <div v-if="contactInfo" class="contact-details">
              <p><i class="fas fa-user"></i> {{ contactInfo.name }}</p>
              <p><i class="fas fa-phone"></i> {{ contactInfo.tel }}</p>
              <p><i class="fas fa-envelope"></i> {{ contactInfo.email }}</p>
              <p><i class="fas fa-map-marker-alt"></i> {{ contactInfo.address }}</p>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { ApiService } from '@/services/api'

export default {
  name: 'AdoptionCasesWithAPI',
  data() {
    return {
      // 数据状态
      loading: false,
      error: null,
      cases: [],
      totalCases: 0,
      totalPages: 0,
      
      // 分页参数
      currentPage: 1,
      pageSize: 6,
      
      // 搜索参数
      searchInput: '',
      searchKeyword: '',
      currentStatusFilter: '',
      
      // 侧边栏数据
      recommendedKnowledge: [],
      knowledgeLoading: false,
      contactInfo: null,
      
      // 筛选选项
      statusFilters: [
        { label: '全部', value: '' },
        { label: '已成功领养', value: '已成功领养' },
        { label: '等待领养', value: '等待领养' },
        { label: '救助康复中', value: '救助康复中' }
      ]
    }
  },
  async created() {
    // 从URL参数获取搜索关键词
    this.searchKeyword = this.$route.query.search || ''
    this.searchInput = this.searchKeyword
    this.currentPage = parseInt(this.$route.query.page) || 1
    
    // 初始化数据
    await this.fetchCases()
    await this.fetchSidebarData()
  },
  watch: {
    '$route.query'(newQuery) {
      // 监听路由变化，更新搜索参数
      this.searchKeyword = newQuery.search || ''
      this.searchInput = this.searchKeyword
      this.currentPage = parseInt(newQuery.page) || 1
      this.fetchCases()
    }
  },
  methods: {
    // 获取领养案例数据
    async fetchCases() {
      this.loading = true
      this.error = null
      
      try {
        const params = {
          page: this.currentPage,
          pageSize: this.pageSize
        }
        
        if (this.searchKeyword) {
          params.search = this.searchKeyword
        }
        
        const response = await ApiService.getAdoptionCases(params)
        
        if (response.success) {
          this.cases = response.data
          this.totalCases = response.total
          this.totalPages = response.totalPages
        } else {
          this.error = response.message || '获取数据失败'
        }
      } catch (error) {
        console.error('获取领养案例失败:', error)
        this.error = '网络错误，请稍后再试'
      } finally {
        this.loading = false
      }
    },
    
    // 获取侧边栏数据
    async fetchSidebarData() {
      this.knowledgeLoading = true
      
      try {
        // 并行获取知识文章和联系信息
        const [knowledgeResponse, contactResponse] = await Promise.all([
          ApiService.getPetKnowledge({ pageSize: 5 }),
          ApiService.getContactInfo()
        ])
        
        if (knowledgeResponse.success) {
          this.recommendedKnowledge = knowledgeResponse.data
        }
        
        if (contactResponse.success) {
          this.contactInfo = contactResponse.data
        }
      } catch (error) {
        console.error('获取侧边栏数据失败:', error)
      } finally {
        this.knowledgeLoading = false
      }
    },
    
    // 执行搜索
    performSearch() {
      this.searchKeyword = this.searchInput.trim()
      this.currentPage = 1
      this.updateURL()
      this.fetchCases()
    },
    
    // 清除搜索
    clearSearch() {
      this.searchInput = ''
      this.searchKeyword = ''
      this.currentPage = 1
      this.updateURL()
      this.fetchCases()
    },
    
    // 按状态筛选
    filterByStatus(status) {
      this.currentStatusFilter = status
      this.searchInput = status
      this.searchKeyword = status
      this.currentPage = 1
      this.updateURL()
      this.fetchCases()
    },
    
    // 分页跳转
    goToPage(page) {
      if (page >= 1 && page <= this.totalPages && page !== this.currentPage) {
        this.currentPage = page
        this.updateURL()
        this.fetchCases()
        // 滚动到顶部
        window.scrollTo({ top: 0, behavior: 'smooth' })
      }
    },
    
    // 更新URL参数
    updateURL() {
      const query = {}
      
      if (this.searchKeyword) {
        query.search = this.searchKeyword
      }
      
      if (this.currentPage > 1) {
        query.page = this.currentPage
      }
      
      this.$router.push({ query })
    },
    
    // 获取分页数字
    getPageNumbers() {
      const pages = []
      const start = Math.max(1, this.currentPage - 2)
      const end = Math.min(this.totalPages, this.currentPage + 2)
      
      for (let i = start; i <= end; i++) {
        pages.push(i)
      }
      
      return pages
    },
    
    // 获取状态样式类
    getStatusClass(status) {
      const statusClasses = {
        '已成功领养': 'status-adopted',
        '等待领养': 'status-waiting',
        '救助康复中': 'status-recovery'
      }
      return statusClasses[status] || 'status-default'
    },
    
    // 处理图片加载错误
    handleImageError(event) {
      event.target.src = require('@/assets/images/placeholder.jpg') // 需要准备一个占位图片
      event.target.alt = '图片加载失败'
    },
    
    // 格式化日期
    formatDate(date) {
      if (!date) return ''
      const d = new Date(date)
      return `${d.getMonth() + 1}/${d.getDate()}`
    }
  }
}
</script>

<style scoped>
.cases-page {
  min-height: 100vh;
  background: #f8f9fa;
}

.page-header {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  padding: 4rem 0 2rem;
  margin-bottom: 2rem;
}

.page-title {
  font-size: 2.5rem;
  font-weight: bold;
  margin-bottom: 0.5rem;
}

.page-subtitle {
  font-size: 1.1rem;
  opacity: 0.9;
}

.adoption-card {
  background: white;
  border-radius: 15px;
  overflow: hidden;
  box-shadow: 0 4px 15px rgba(0,0,0,0.1);
  transition: all 0.3s ease;
  height: 100%;
}

.adoption-card:hover {
  transform: translateY(-8px);
  box-shadow: 0 8px 30px rgba(0,0,0,0.15);
}

.adoption-image-wrapper {
  position: relative;
  height: 200px;
  overflow: hidden;
}

.adoption-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: transform 0.3s ease;
}

.adoption-card:hover .adoption-image {
  transform: scale(1.1);
}

.adoption-status {
  position: absolute;
  top: 10px;
  right: 10px;
  padding: 4px 8px;
  border-radius: 20px;
  font-size: 12px;
  font-weight: bold;
  color: white;
}

.status-adopted { background: #28a745; }
.status-waiting { background: #ffc107; color: #212529; }
.status-recovery { background: #17a2b8; }
.status-default { background: #6c757d; }

.adoption-info {
  padding: 1.5rem;
}

.adoption-name {
  font-size: 1.2rem;
  font-weight: bold;
  margin-bottom: 0.5rem;
  color: #333;
}

.adoption-details {
  margin-bottom: 0.75rem;
}

.detail-item {
  display: inline-block;
  background: #e9ecef;
  padding: 2px 8px;
  border-radius: 10px;
  font-size: 12px;
  margin-right: 5px;
  color: #495057;
}

.adoption-description {
  color: #666;
  font-size: 14px;
  line-height: 1.5;
  margin-bottom: 1rem;
}

.adoption-actions {
  text-align: center;
}

.sidebar-title {
  color: #333;
  font-size: 1.1rem;
  font-weight: bold;
  margin-bottom: 1rem;
  padding-bottom: 0.5rem;
  border-bottom: 2px solid #007bff;
}

.search-box,
.quick-filters,
.knowledge-recommend,
.contact-info {
  background: white;
  padding: 1.5rem;
  border-radius: 10px;
  box-shadow: 0 2px 10px rgba(0,0,0,0.05);
}

.filter-buttons .btn.active {
  background-color: #007bff;
  border-color: #007bff;
  color: white;
}

.knowledge-list {
  list-style: none;
  padding: 0;
}

.knowledge-list li {
  padding: 0.5rem 0;
  border-bottom: 1px solid #eee;
}

.knowledge-list li:last-child {
  border-bottom: none;
}

.knowledge-list a {
  color: #333;
  text-decoration: none;
  font-size: 14px;
  display: block;
  margin-bottom: 0.25rem;
}

.knowledge-list a:hover {
  color: #007bff;
}

.contact-details p {
  margin-bottom: 0.5rem;
  font-size: 14px;
  color: #666;
}

.contact-details i {
  width: 16px;
  color: #007bff;
  margin-right: 0.5rem;
}

.no-data {
  text-align: center;
  padding: 3rem;
}

.no-data-image {
  width: 150px;
  opacity: 0.5;
  margin-bottom: 1rem;
}

@media (max-width: 768px) {
  .page-header {
    padding: 2rem 0 1rem;
  }
  
  .page-title {
    font-size: 2rem;
  }
  
  .adoption-card {
    margin-bottom: 1rem;
  }
}
</style>
